package com.mini.service;

import cn.hutool.core.collection.CollectionUtil;
import com.google.common.collect.Lists;
import com.mini.conditon.ChanceCommentCondition;
import com.mini.config.BusinessException;
import com.mini.model.BusinessChanceCommentRecord;
import com.mini.model.BusinessTraditionChance;
import com.mini.repository.BusinessChanceCommentRecordRepository;
import com.mini.util.CalendarUtil;
import com.mini.vo.BusinessTraditionChanceVO;
import com.mini.vo.PageResultVO;
import com.mini.vo.UserVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ChanceCommentService extends BaseService{

    @Autowired
    private BusinessChanceCommentRecordRepository chanceCommentRecordRepository;
    @Autowired
    private BusinessTraditionChanceService traditionChanceService;

    public BusinessChanceCommentRecord insert(Long chanceId, String comment, UserVO operateUser){

        if(chanceId == null || StringUtils.isBlank(comment) || operateUser == null){
            throw new IllegalArgumentException("参数为空！");
        }

        BusinessTraditionChance chance = traditionChanceService.findOne(chanceId);
        if(chance == null){
            throw new BusinessException("未查询到该机会！chanceId="+ chanceId);
        }

        BusinessChanceCommentRecord record = BusinessChanceCommentRecord.builder()
                .chanceId(chanceId)
                .comment(comment)
                .createTime(new Date())
                .createUserId(operateUser.getId())
                .build();

        return this.chanceCommentRecordRepository.save(record);

    }

    public Map<Long, BusinessChanceCommentRecord> findCommentsByChanceId(Collection<Long> chanceIds){
        Map<Long, BusinessChanceCommentRecord> map = new HashMap<>();
        if(CollectionUtil.isEmpty(chanceIds)){
            return map;
        }
        List<BusinessChanceCommentRecord> list = this.chanceCommentRecordRepository.findByChanceIdIn(new HashSet(chanceIds));

        if(CollectionUtils.isEmpty(list)){
            return map;
        }

        Map<Long, List<BusinessChanceCommentRecord>> listMap = list.stream().collect(Collectors.groupingBy(BusinessChanceCommentRecord :: getChanceId));

        //按创建时间倒叙排序
        for(Map.Entry<Long, List<BusinessChanceCommentRecord>> entry : listMap.entrySet()){
            Long chanceId = entry.getKey();
            List<BusinessChanceCommentRecord> value = entry.getValue();
            if(!CollectionUtils.isEmpty(value)){
                value.sort(Comparator.comparing(BusinessChanceCommentRecord :: getCreateTime).reversed());
            }
            map.put(chanceId, value.get(0));

        }

        return map;
    }

    public BusinessChanceCommentRecord findLastedRecord(Long chanceId){
        if(chanceId == null ){
            throw new IllegalArgumentException("参数为空！");
        }

        return this.chanceCommentRecordRepository.findFirstByChanceIdOrderByCreateTimeDesc(chanceId);

    }


    public PageResultVO<BusinessChanceCommentRecord> page(ChanceCommentCondition condition){

        if(condition == null){
            throw new IllegalArgumentException("参数为空！");
        }
        if(condition.getChanceId() == null){
            throw new IllegalArgumentException("机会ID为必填项");
        }

        Specification<BusinessChanceCommentRecord> specification = new Specification<BusinessChanceCommentRecord>() {
            @Override
            public Predicate toPredicate(Root<BusinessChanceCommentRecord> root, CriteriaQuery<?> query, CriteriaBuilder cb) {

                List<Predicate> predicateList = Lists.newArrayList();
                //机会id
                Optional.ofNullable(condition.getChanceId()).ifPresent(o -> predicateList.add(cb.equal(root.get("chanceId").as(Long.class), o)));

                //开始时间
                if(StringUtils.isNotBlank(condition.getBeginTime())){
                    Date beginTime = CalendarUtil.parseDefaultDate(condition.getBeginTime() + " 00:00:00");
                    predicateList.add(cb.greaterThanOrEqualTo(root.get("createTime").as(Date.class), beginTime));
                }
                //结束时间
                if(StringUtils.isNotBlank(condition.getEndTime())) {
                    Date endTime = CalendarUtil.parseDefaultDate(condition.getEndTime() + " 23:59:59");
                    predicateList.add(cb.lessThanOrEqualTo(root.get("createTime").as(Date.class), endTime));
                }

                return cb.and(predicateList.toArray(new Predicate[predicateList.size()]));
            }
        };

        Sort sort = new Sort(Sort.Direction.DESC, Lists.newArrayList("createTime"));
        Pageable pageable = buildPageRequest(condition.getPageNumber(), condition.getPageSize(), sort);

        Page<BusinessChanceCommentRecord> page = this.chanceCommentRecordRepository.findAll(specification, pageable);
        List<BusinessChanceCommentRecord> list = page.getContent();


        PageResultVO<BusinessChanceCommentRecord> result = new PageResultVO<>();
        result.setRows(list);
        result.setTotal(page.getTotalElements());

        return result;
    }



}
